import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, setToken, setIDaaSAuth} from '@/utils/auth' // get token from cookie
import { initCookieDict } from '@/utils/dict' // cookie字典
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

 
router.beforeEach(async(to, from, next) => {
    // start progress bar
    NProgress.start()
        // set page title
    document.title = getPageTitle(to.meta.title)
    const hasToken = getToken()
    if (hasToken) {
        if (to.path === '/login') {
            next({ path: '/' })
            NProgress.done() 
        } else {
            const hasRoles = store.getters.roles && store.getters.roles.length > 0
            if (hasRoles) {
                sessionStorage.setItem('pathName', to.path)
                next()
            } else {
                try {
                    const roles = await store.dispatch('user/getInfo')
                    const accessRoutes = await store.dispatch('permission/generateRoutes', ['admin'])
                    // 获取字典缓存
                    initCookieDict()
                    router.addRoutes(accessRoutes)
                    const pathName = sessionStorage.getItem('pathName') // 暂存上一个路由
                    next({ ...to, replace: true, path: pathName })
                    next()
                } catch (error) {
                    await store.dispatch('user/resetToken')
                    Message.error(error || 'Has Error')
                    next(`/login?redirect=${to.path}`)
                    NProgress.done()
                }
            }
        }
    } else {
        // 获取URL 地址中的参数
        const token = to.query.token
        const auth = to.query['IDaaS-Auth']
        if(token){// 直接登录
            setIDaaSAuth(auth)
            await store.dispatch('user/setToken',token)
            router.addRoutes([])
            next('/login')
            // dashboard
            NProgress.done()
        }else{
            if (whiteList.indexOf(to.path) !== -1) {
                next()
            } else {
                next(`/login?redirect=${to.path}`)
                NProgress.done()
            }
        }
    }
})

router.afterEach(() => {
    NProgress.done()
})